<template>
  <div>
<div  v-if="!pageControll">
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="参保方案" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入参保方案"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['cbfa:cbfa:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['cbfa:cbfa:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['cbfa:cbfa:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['cbfa:cbfa:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cbfaList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="参保方案名称" align="center" prop="name" />
      <el-table-column label="参保城市" align="center" prop="city" />
      <el-table-column label="社保方案" align="center" prop="categoryShebaoName" />
      <el-table-column label="公积金方案" align="center" prop="categoryGjjName" />
   
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
           <el-button 
        link 
        type="primary" 
        icon="Edit" 
        @click="handleAdjustScheme(scope.row)"
      >调整</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['cbfa:cbfa:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参保方案对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="cbfaRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="参保方案" prop="name">
          <el-input v-model="form.name" placeholder="请输入参保方案名称" />
        </el-form-item>
        <el-form-item label="社保" prop="categoryShebaoName">
          <el-input v-model="form.categoryShebaoName" placeholder="社保方案" />
        </el-form-item>
        <el-form-item label="公积金" prop="categoryGjjName">
          <el-input v-model="form.categoryGjjName" placeholder="公积金方案" />
        </el-form-item>
        <el-form-item label="创建城市" prop="city">
           <el-input v-model="form.city" placeholder="城市" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  </div>





  <div  v-if="pageControll"  style="border-color: #ee4866;">
    <el-button @click="handleAdjustScheme1">返回</el-button>
<div class="payroll-config-container">
    <!-- 社保配置卡片 -->
    <el-card class="config-card" shadow="never">
      <template #header>
        <span class="card-header">社保方案</span>
      </template>

      <el-form-item label="社保方案类型">
        <el-select v-model="housingFormData.schemeType" placeholder="请选择">
          <el-option label="
上海社保唯一标准" value="shanghai"></el-option>
          <el-option label="
北京社保唯一标准" value="beijing"></el-option>
          <el-option label="自定义方案" value="custom"></el-option>
        </el-select>
      </el-form-item>


      <div class="form-section">
        <el-form ref="socialForm" :model="socialFormData" label-width="0">
          <table class="form-table">
            <thead>
              <tr>
                <th>险种名称</th>
                <th>基数下限</th>
                <th>基数上限</th>
                <th>公司比例(%)</th>
                <th>公司固定金额(元)</th>
                <th>个人比例(%)</th>
                <th>个人固定金额(元)</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in socialFormData" :key="index">
                <td>
                  <el-form-item>
                    <el-input v-model="item.insuranceType" />
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.baseMin" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.baseMax" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.companyRatio" type="number" :precision="2">
                      <template #append>%</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.companyFixedAmount" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.personalRatio" type="number" :precision="2">
                      <template #append>%</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.personalFixedAmount" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-button type="danger" icon="Delete" circle @click="removeSocialItem(index)" />
                </td>
              </tr>
            </tbody>
          </table>

          <div class="action-buttons">
            <el-button type="primary" icon="Plus" @click="addSocialItem">新增险种</el-button>
            <el-button type="warning" @click="resetSocialForm">重置</el-button>
          </div>
        </el-form>
      </div>
    </el-card>

    <!-- 公积金配置卡片 -->
    <el-card class="config-card" shadow="never" style="margin-top: 20px;">
      <template #header>
        <span class="card-header">公积金方案</span>
      </template>


      <el-form-item label="公积金方案类型">
        <el-select v-model="housingFormData.schemeType" placeholder="请选择">
          <el-option label="上海公积金8+8" value="shanghai"></el-option>
          <el-option label="北京公积金12%" value="beijing"></el-option>
          <el-option label="自定义方案" value="custom"></el-option>
        </el-select>
      </el-form-item>


      <div class="form-section">
        <el-form ref="housingForm" :model="housingFormData" label-width="0">
          <table class="form-table">
            <thead>
              <tr>
                <th>公积金类型</th>
                <th>基数下限</th>
                <th>基数上限</th>
                <th>公司比例(%)</th>
                <th>公司固定金额(元)</th>
                <th>个人比例(%)</th>
                <th>个人固定金额(元)</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in housingFormData" :key="index">
                <td>
                  <el-form-item>
                    <el-input v-model="item.insuranceType" readonly />
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.baseMin" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.baseMax" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.companyRatio" type="number" :precision="2">
                      <template #append>%</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.companyFixedAmount" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.personalRatio" type="number" :precision="2">
                      <template #append>%</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.personalFixedAmount" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-button type="danger" icon="Delete" circle @click="removeHousingItem(index)" />
                </td>
              </tr>
            </tbody>
          </table>

          <div class="action-buttons">
            <el-button type="primary" icon="Plus" @click="addHousingItem">新增项目</el-button>
            <el-button type="warning" @click="resetHousingForm">重置</el-button>
          </div>
        </el-form>
      </div>
    </el-card>
    </div>
    <!-- 费用统计卡片 -->
    <el-card class="stats-card" shadow="never" style="margin-top: 20px;">
      <template #header>
        <span class="card-header">费用统计</span>
      </template>
      <div class="stats-container">
        <div class="stat-item">
          <div class="stat-label">个人缴费总计：</div>
          <div class="stat-value highlight">{{ totalPersonal | currency }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">企业缴费总计：</div>
          <div class="stat-value highlight">{{ totalCompany | currency }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">全部缴费合计：</div>
          <div class="stat-value highlight">{{ totalAll | currency }}</div>
        </div>
      </div>
    </el-card>

    <!-- 底部操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="saveConfig">保存</el-button>
      <el-button @click="cancelEdit">取消</el-button>
    </div>
  </div>
  </div>


</template>

<script setup name="Cbfa">
import { listCbfa, getCbfa, delCbfa, addCbfa, updateCbfa ,getAdjustList,delHousingItem,updateInsurancePlanDetail} from "@/api/cbfa/cbfa";
import { ref, computed, onMounted,onUnmounted  } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();
const tableData = ref([]);
const pageControll = ref(false); // 控制页面显示
const { proxy } = getCurrentInstance()
const cbfaList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const categoryId = ref("")
const socialFormData = ref([]); 
const housingFormData = ref([]); 
let initialHousingData = []; // 公积金初始数据
let initialSocialData = [];  // 社保初始数据



// 费用统计
const totalPersonal = computed(() => {
  return calculateTotal(socialFormData.value, 'personal') +
    calculateTotal(housingFormData.value, 'personal');
});

const totalCompany = computed(() => {
  return calculateTotal(socialFormData.value, 'company') +
    calculateTotal(housingFormData.value, 'company');
});

const totalAll = computed(() => totalPersonal.value + totalCompany.value);
// 计算总费用
function calculateTotal(items, type) {
  if (!Array.isArray(items)) {
    return 0;
  }
  return items.reduce((sum, item) => {
    const rate = type === 'company' ? item.companyRatio : item.personalRatio;
    const fixed = type === 'company' ? item.companyFixedAmount : item.personalFixedAmount;

    if (rate > 0) {
      return sum + (rate / 100 * (item.baseMax + item.baseMin) / 2);
    } else if (fixed > 0) {
      return sum + fixed * 2; // 假设上下限相同
    } else {
      return sum + ((item.baseMax + item.baseMin) / 2);
    }
  }, 0);
}

// 保存配置
const saveConfig = async () => {
  try {
    // 准备要提交的数据
   

    socialFormData.value.forEach(e => {
   updateInsurancePlanDetail(e);
    });

     housingFormData.value.forEach(e => {
   updateInsurancePlanDetail(e);
    });
    // 调用修改社保方案详情接口

    ElMessage.success('配置已保存！');
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存配置失败，请重试');
  }
  finally {console.log("==========",socialFormData.value)}
};


// 新增/删除方法
const addSocialItem = () => {
  socialFormData.value.push({
    name: '',
    baseMin: 0,
    baseMax: 0,
    companyRate: 0,
    companyFixed: 0,
    personalRate: 0,
    personalFixed: 0
  });
};

// 删除公积金项目
const removeSocialItem = async (index) => {
  const item = socialFormData.value[index];
  if (!item.id) {
    socialFormData.value.splice(index, 1);
    ElMessage.success('删除成功！');
    return;
  }
  try {
    // 调用删除接口，传递包含单个 id 的数组
    await delHousingItem([item.id]); 
    socialFormData.value.splice(index, 1);
    ElMessage.success('删除成功！');
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败，请重试！');
  }
};

const addHousingItem = () => {
  housingFormData.value.push({
    type: 'housing',
    name: '',
    baseMin: 0,
    baseMax: 0,
    companyRate: 0,
    companyFixed: 0,
    personalRate: 0,
    personalFixed: 0
  });
};

// 删除公积金项目
const removeHousingItem = async (index) => {
  const item = housingFormData.value[index];
  if (!item.id) {
    housingFormData.value.splice(index, 1);
    ElMessage.success('删除成功！');
    return;
  }
  try {
    // 调用删除接口，传递包含单个 id 的数组
    await delHousingItem([item.id]); 
    housingFormData.value.splice(index, 1);
    ElMessage.success('删除成功！');
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败，请重试！');
  }
};

const resetHousingForm = () => {
  housingFormData.value = [...initialHousingData]; // 恢复初始数据
};

// 重置社保数据
const resetSocialForm = () => {
  socialFormData.value = [...initialSocialData]; // 恢复初始数据
};






// 处理调整按钮点击事件
const handleAdjustScheme = async(row) => {


 pageControll.value = true; // 显示调整页面
 try {
   console.log("==========",categoryId.value)
 categoryId.value=row.categoryShebaoId;
 console.log(categoryId.value)
    const response = await getAdjustList(categoryId.value) 
    if (response.rows) {
      socialFormData.value = response.rows
      initialSocialData = [...response.rows];
    }

    categoryId.value=row.categoryGjjId;
 console.log(categoryId.value)
    const res = await getAdjustList(categoryId.value) 
    if (res.rows) {
      housingFormData.value = res.rows
       initialHousingData = [...res.rows];
    }

  } catch (error) {
    console.error('获取参保方案详情失败:', error)
  }finally {console.log("==========",socialFormData.value )}
  }
;

const handleAdjustScheme1 = (row) => {
 pageControll.value = false; // 关闭调整页面
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    city: null,
  },
  rules: {
    name: [
      { required: true, message: "参保方案名称不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)






/** 查询参保方案列表 */
function getList() {
  loading.value = true
  listCbfa(queryParams.value).then(response => {
    cbfaList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}
function cancelEdit() {
  pageControll.value = false; // 关闭调整页面
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    city: null,
    categoryShebaoName: null,
    categoryGjjName: null,
    delFlag: [],
    city: null
  }
  proxy.resetForm("cbfaRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加参保方案"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getCbfa(_id).then(response => {
    form.value = response.data
    if (typeof form.value.delFlag !== 'string') {
      form.value.delFlag = String(form.value.delFlag);
    }
    form.value.delFlag = form.value.delFlag.split(",")
    open.value = true
    title.value = "修改参保方案"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["cbfaRef"].validate(valid => {
    if (valid) {
      form.value.delFlag = form.value.delFlag.join(",")
      if (form.value.id != null) {
        updateCbfa(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCbfa(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除参保方案编号为"' + _ids + '"的数据项？').then(function() {
    return delCbfa(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('cbfa/cbfa/export', {
    ...queryParams.value
  }, `cbfa_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.payroll-config-container {
  padding: 20px;
}

.config-card {
  margin-bottom: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.form-section {
  padding: 20px;
}

.item-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.item-row :deep(.el-form-item) {
  margin-bottom: 0;
}

.item-row :deep(.el-form-item__content) {
  margin-left: 0 !important;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.stats-card {
  flex: 1;
}

.stats-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.stat-label {
  color: #606266;
}

.highlight {
  color: #409EFF;
  font-weight: bold;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  padding: 15px;
  background-color: #f9fafc;
  border-top: 1px solid #e4e7ed;
}

.payroll-config-container {
  padding: 20px;
  max-width: 80%;
  /* 限制容器最大宽度为80% */
  margin: 0 auto;
  /* 水平居中 */
}

.config-card {
  margin-bottom: 20px;
}

.item-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: nowrap;
  /* 禁止换行 */
}

/* 优化列布局 */
.el-col {
  flex: 0 0 auto;
  /* 禁止列元素缩放 */
}

/* 调整按钮栏布局 */
.action-buttons,
.action-bar {
  justify-content: flex-start;
  /* 按钮左对齐减少右侧空白 */
  gap: 10px;
  /* 增加按钮间距 */
}

/* 优化统计卡片布局 */
.stats-container {
  max-width: 100%;
  /* 确保统计卡片不超出容器 */
}

.form-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.form-table th,
.form-table td {
  border: 1px solid #EBEEF5;
  padding: 10px;
  text-align: left;
}

.form-table th {
  background-color: #F5F7FA;
  font-weight: 500;
}

.form-table td {
  vertical-align: middle;
}

/* 表单元素在表格中的样式 */
.form-table .el-form-item {
  margin-bottom: 0;
}

.form-table .el-input,
.form-table .el-select {
  width: 100%;
}

/* 操作按钮样式 */
.form-table .el-button {
  padding: 5px;
}

/* 其他样式保持不变 */
.payroll-config-container {
  padding: 20px;
  max-width: 1200px;
  /* 限制最大宽度 */
  margin: 0 auto;
}

.config-card {
  margin-bottom: 20px;
}

.action-buttons,
.action-bar {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.stats-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.stat-label {
  color: #606266;
}

.highlight {
  color: #409EFF;
  font-weight: bold;
}
</style>
